import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim/models/circle_models.dart';
import 'package:openim_common/openim_common.dart';
import 'post_search_logic.dart';
import '../../../routes/app_navigator.dart';

class PostSearchPage extends StatelessWidget {
  final logic = Get.find<PostSearchLogic>();

  PostSearchPage({super.key});

  @override
  Widget build(BuildContext context) {
    return TouchCloseSoftKeyboard(
      child: Scaffold(
        backgroundColor: Styles.c_F8F9FA,
        appBar: _buildAppBar(),
        body: RefreshIndicator(
          onRefresh: () => logic.performSearch(),
          child: Obx(() {
            if (!logic.hasSearched.value) {
              return _buildEmptyState();
            }
            if (logic.isSearching.value) {
              return _buildLoadingState();
            }
            if (logic.results.isEmpty) {
              return _buildNoResultState(logic.searchCtrl.text.trim());
            }
            return _buildResultList();
          }),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Styles.c_FFFFFF,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Styles.c_0C1C33),
        onPressed: () => Get.back(),
      ),
      title: Container(
        height: 36.h,
        decoration: BoxDecoration(
          color: Styles.c_F8F9FA,
          borderRadius: BorderRadius.circular(18.r),
        ),
        child: TextField(
          controller: logic.searchCtrl,
          focusNode: logic.focusNode,
          autofocus: true,
          decoration: InputDecoration(
            hintText: '搜索帖子',
            hintStyle: Styles.ts_8E9AB0_16sp,
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
            suffixIcon: ValueListenableBuilder<TextEditingValue>(
              valueListenable: logic.searchCtrl,
              builder: (context, value, child) {
                return value.text.trim().isNotEmpty
                    ? IconButton(
                        icon: Icon(Icons.clear, size: 20.w, color: Styles.c_8E9AB0),
                        onPressed: logic.clearSearch,
                      )
                    : const SizedBox.shrink();
              },
            ),
          ),
          style: Styles.ts_0C1C33_14sp,
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => logic.performSearch(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: logic.performSearch,
          child: Text('搜索', style: Styles.ts_0089FF_16sp),
        ),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.search, size: 64.w, color: Styles.c_8E9AB0),
          16.verticalSpace,
          Text('输入关键词开始搜索', style: Styles.ts_8E9AB0_16sp),
        ],
      ),
    );
  }

  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Styles.c_0089FF),
          16.verticalSpace,
          Text('搜索中...', style: Styles.ts_8E9AB0_16sp),
        ],
      ),
    );
  }

  Widget _buildNoResultState(String kw) {
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Container(
        height: MediaQuery.of(Get.context!).size.height * 0.6,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.search_off, size: 64.w, color: Styles.c_8E9AB0),
            16.verticalSpace,
            Text('没有找到与“$kw”相关的帖子', style: Styles.ts_8E9AB0_16sp),
            8.verticalSpace,
            Text('试试更换关键词或清除搜索', style: Styles.ts_8E9AB0_12sp),
            16.verticalSpace,
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                OutlinedButton.icon(
                  onPressed: logic.clearSearch,
                  icon: const Icon(Icons.clear),
                  label: const Text('清除搜索'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildResultList() {
    return ListView.builder(
      physics: const AlwaysScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(vertical: 8.h),
      itemCount: logic.results.length,
      itemBuilder: (context, index) {
        final post = logic.results[index];
        return _buildResultItem(post);
      },
    );
  }

  Widget _buildResultItem(CirclePost post) {
    return GestureDetector(
      onTap: () => AppNavigator.startPostDetail(post.id),
      child: Card(
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      child: Padding(
        padding: EdgeInsets.all(12.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CircleAvatar(
                  radius: 16.w,
                  backgroundColor: Styles.c_F8F9FA,
                  backgroundImage:
                      post.userAvatar.isNotEmpty ? NetworkImage(post.userAvatar) : null,
                  child: post.userAvatar.isEmpty
                      ? Icon(Icons.person, size: 16.w, color: Styles.c_8E9AB0)
                      : null,
                ),
                8.horizontalSpace,
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(post.userName, style: Styles.ts_0C1C33_14sp),
                      2.verticalSpace,
                      Text('${post.circleDisplayName} · ${post.timeAgo}',
                          style: Styles.ts_8E9AB0_12sp),
                    ],
                  ),
                ),
              ],
            ),
            8.verticalSpace,
            Text(
              post.content,
              style: Styles.ts_0C1C33_14sp,
              maxLines: 4,
              overflow: TextOverflow.ellipsis,
            ),
            if (post.tags.isNotEmpty) ...[
              8.verticalSpace,
              Wrap(
                spacing: 6.w,
                runSpacing: 6.h,
                children: post.tags.map((t) {
                  return Container(
                    padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                    decoration: BoxDecoration(
                      color: Styles.c_F8F9FA,
                      borderRadius: BorderRadius.circular(12.r),
                      border: t.color != null
                          ? Border.all(color: Color(int.parse('0xFF${t.color!.substring(1)}')))
                          : null,
                    ),
                    child: Text(t.name, style: Styles.ts_8E9AB0_12sp),
                  );
                }).toList(),
              ),
            ],
          ],
        ),
      ),
    ),
  );
  }
}